import router from "./router";
import axios from "axios";
import Element from "element-ui"
import qs from "qs";

axios.defaults.baseURL = "https://www.codingyt.com"
// axios.defaults.baseURL = "http://124.221.82.106:8085/"

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    },
    paramsSerializer: params => {
        return qs.stringify(params, {indices: false})
    }
})

request.interceptors.request.use(config => {
    config.headers['Authorization'] = localStorage.getItem("token")
    return config
})

request.interceptors.response.use(
    response => {
        let res = response.data

        if (res.code === 200) {
            return response
        } else {
            Element.Message.error(!res.msg ? '系统异常' : res.msg)
            return Promise.reject(response.data.msg)
        }
    },
    error => {
        console.log(error)
        if (error.response.data) {
            error.massage = error.response.data.msg
        }
        if (error.response.status === 401) {
            localStorage.removeItem('token');
            router.push("/login")
        }
        Element.Message.error(error.massage, {duration: 3000})
        return Promise.reject(error)
    }
)

export default request
